import { Component } from 'react';
import { View } from '@tarojs/components';
import Absolute from '../Absolute';
import './index.scss';

class PullView extends Component {
  state = {
    visible: false,
    aminated: false,
  };

  componentDidMount() {}

  componentDidUpdate(prevProps) {
    if (this.props.open && !prevProps.open) {
      this.open();
    } else if (!this.props.open && prevProps.open) {
      this.close();
    }
  }

  componentWillUnmount() {
    clearTimeout(this.timer);
  }

  timer = 0;

  overlayClick = () => {
    const { modal } = this.props;
    if (modal) return;
    this.close();
  };

  open = () => {
    this.setState(
      {
        visible: true,
      },
      () => {
        this.timer = setTimeout(() => {
          this.setState({
            aminated: true,
          });
        }, 10);
      },
    );
  };

  close = async () => {
    this.setState(
      {
        aminated: false,
      },
      () => {
        this.timer = setTimeout(() => {
          this.setState({
            visible: false,
          });
          this.props.onClose?.();
        }, 200);
      },
    );
  };

  stopPropagation = e => {
    e.stopPropagation?.();
  };

  render() {
    const { visible, aminated } = this.state;
    const { side = 'bottom', style = {}, overlayOpacity = 0.5, children } = this.props;
    return (
      <Absolute>
        {visible && (
          <>
            <View
              className='pd-pull-view'
              style={{ backgroundColor: aminated ? `rgba(0, 0, 0, ${overlayOpacity})` : 'rgba(0, 0, 0, 0)' }}
              onClick={this.stopPropagation}>
              <View className='pd-pull-view__other' onClick={this.overlayClick}></View>
            </View>
            <View className={`pd-pull-view__main pd-pull-view__main--${side}${aminated ? ' pd-pull-view__main--show' : ''}`} style={style}>
              {children}
            </View>
          </>
        )}
      </Absolute>
    );
  }
}
export default PullView;
